package com.guc.md

import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.MenuItem
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.palette.graphics.Palette
import com.guc.gviewbinding.inflate
import com.guc.md.databinding.ActivityThirdBinding

/**
 * Created by Guc on 2021/5/21.
 * Description：Palette库来获取图片的主要色彩
 */
class ThirdActivity : AppCompatActivity() {

    private val binding: ActivityThirdBinding by inflate()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setSupportActionBar(binding.toolbar)
        supportActionBar?.run { //显示导航按钮
            setDisplayHomeAsUpEnabled(true)
            setHomeAsUpIndicator(R.drawable.icon_back)
        }
        binding.btnGetColor.setOnClickListener {
            getColorFromPicture()
            playRevealAnimation()
        }
        binding.nextPage.setOnClickListener {
            startActivity(Intent(this,ForthActivity::class.java))
        }
    }

    /**
     * 从图片中获取主要颜色
     */
    private fun getColorFromPicture() {
        val bm = BitmapFactory.decodeResource(resources, R.drawable.icon_header)
        val palette = Palette.Builder(bm).generate()
        binding.apply {
            ivVibrantDark.background =
                ColorDrawable(palette.darkVibrantSwatch?.rgb ?: Color.WHITE)
            ivVibrantLight.background =
                ColorDrawable(palette.lightVibrantSwatch?.rgb ?: Color.WHITE)
            ivMutedDark.background =
                ColorDrawable(palette.darkMutedSwatch?.rgb ?: Color.WHITE)
            ivMutedLight.background =
                ColorDrawable(palette.lightMutedSwatch?.rgb ?: Color.WHITE)
        }
    }

    /**
     * 展示动画
     */
    private fun playRevealAnimation() {
        val ani = ViewAnimationUtils.createCircularReveal(
            binding.iv,
            binding.iv.width / 2,
            binding.iv.height / 2,
            0f,
            binding.iv.width.toFloat() / 2,
        )
        ani.interpolator = AccelerateDecelerateInterpolator()
        ani.duration = 2000
        ani.start()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        this.finish()
        return super.onOptionsItemSelected(item)
    }
}